package com.graduation.smartparkingplatform.ServiceImpl;

import com.alibaba.fastjson.JSON;
import com.graduation.smartparkingplatform.Dao.ClientMapper;
import com.graduation.smartparkingplatform.Pojo.*;
import com.graduation.smartparkingplatform.Service.ClientService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class ClientServiceImpl implements ClientService {

  @Autowired private ClientMapper clientMapper;
  @Autowired private RedisTemplate redisTemplate;

  //  添加用户意见表
  public Boolean addOpinion(String title, String describe, String tel, String fileUrl) {
    // 获取当前时间
    Calendar calendar = Calendar.getInstance();
    // 定义时间格式化
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String nowTime = formatter.format(calendar.getTime());
    return clientMapper.addOpinion(title, describe, tel, fileUrl, nowTime);
  }

  //  客户端获取停车位列表信息
  public SpaceInfo getSpaceInfo() {
    SpaceInfo spaceInfo = new SpaceInfo();
    List<SpaceInfo2> spaceInfo2List = new ArrayList<>();
    String patternKey = "spaceNo_*";
    try {
      Set<String> keys = redisTemplate.keys(patternKey);
      Integer freeSpace = 0;
      for (String str : keys) {
        SpaceInfo2 spaceInfo2 = new SpaceInfo2();
        String jsonStr = (String) redisTemplate.opsForValue().get(str);
        Space space = JSON.parseObject(jsonStr, Space.class);
        Integer spaceNo = space.getSpace_no();
        String space_carPlate = space.getCar_plate();
        Boolean spaceChargeType = space.getSpace_charge_type();
        Boolean spaceStatus = space.getSpace_status();
        Integer spaceId = space.getSpace_id();
        String region = clientMapper.getRegion(spaceId);
        spaceInfo2.setRegion(region);
        spaceInfo2.setSpaceNo(spaceNo);
        spaceInfo2.setSpaceChargeType(spaceChargeType);
        spaceInfo2.setSpaceStatus(spaceStatus);
        spaceInfo2List.add(spaceInfo2);
        if (space_carPlate == null || space_carPlate.equals("")) {
          freeSpace++;
        }
      }
      spaceInfo.setAllSpace(keys.size());
      spaceInfo.setFreeSpace(freeSpace);
      spaceInfo.setSpaceInfo2(spaceInfo2List);
    } catch (Exception e) {
      log.error("Client getSpaceInfo error-" + e);
      e.printStackTrace();
      return spaceInfo;
    }
    return spaceInfo;
  }

  //  客户端绑定车位
  public Boolean chooseSpace(Integer spaceId, String carPlate, String tel) {
    String carTime = (String) redisTemplate.boundValueOps("carPlate_" + carPlate).get();
    try {
      if (carTime == null || carTime.equals("")) {
        return false;
      } else {
        Boolean spaceStatus = clientMapper.spaceStatus(spaceId);
        if (spaceStatus) {
          return clientMapper.chooseSpace(spaceId, carPlate, tel, carTime);
        }
        return false;
      }
    } catch (Exception e) {
      log.error("Client chooseSpace error-" + e);
      e.printStackTrace();
      return false;
    }
    //    finally {
    //      RedisUtil.close(jedis);
    //    }
  }

  // 客户端取消绑定车位
  public String cancelSpace(String carPlate, String tel) {
    String patternKey = "spaceNo_*";
    try {
      Set<String> keys = redisTemplate.keys(patternKey);
      for (String str : keys) {
        String jsonStr = (String) redisTemplate.opsForValue().get(str);
        Space space = JSON.parseObject(jsonStr, Space.class);

        String space_carPlate = space.getCar_plate();
        if (carPlate.equals(space_carPlate)) {
          Integer spaceId = space.getSpace_id();
          String carTel = clientMapper.testTel(spaceId);
          if (carTel.equals(tel)) {
            Boolean cancelSpace = clientMapper.cancelSpace(spaceId, tel);
            return "成功";
          } else {
            return "绑定号码不一致";
          }
        }
      }
      return "此车牌号不存在";
    } catch (Exception e) {
      log.error("Client cancelSpace error-" + e);
      e.printStackTrace();
      return "取绑失败";
    }
  }

  // 客户端根据车牌查询停车位
  public Map<String, String> getSpace(String carPlate) {
    String patternKey = "spaceNo_*";
    try {
      Set<String> keys = redisTemplate.keys(patternKey);
      Map<String, String> result = new HashMap<>();
      for (String str : keys) {
        String jsonStr = (String) redisTemplate.opsForValue().get(str);
        Space space = JSON.parseObject(jsonStr, Space.class);
        String space_carPlate = space.getCar_plate();
        if (carPlate.equals(space_carPlate)) {
          Integer spaceNo = space.getSpace_no();
          Integer spaceId = space.getSpace_id();
          String region = clientMapper.getRegion(spaceId);
          result.put("region", region);
          result.put("spaceNo", spaceNo.toString());
          return result;
        }
      }
    } catch (Exception e) {
      log.error("Client getSpace error-" + e);
      e.printStackTrace();
      return null;
    }
    return null;
  }

  //  客户端支付车位费用
  public Map<String, Double> paying(Integer spaceId) throws ParseException {
    // 获取停车时间
    SpaceAll spaceAll = clientMapper.getSpaceTime(spaceId);
    Boolean chargeType = spaceAll.getSpace_charge_type(); // 获取停车位是否为充电停车位
    String spaceTime = spaceAll.getBilling_start();

    Charge spaceCharge = clientMapper.getSpaceCharge(spaceId);
    Integer chargeFreeTime = spaceCharge.getCharge_free_time();
    BigDecimal chargeMin = spaceCharge.getCharge_min();
    BigDecimal chargingMin = spaceCharge.getCharge_charging_min();
    double chargingMin2 = chargingMin.doubleValue();
    BigDecimal chargingUnitt = spaceCharge.getCharge_charging_unitt();
    double chargingUnitt2 = chargingUnitt.doubleValue() / 60;
    BigDecimal chargeMax = spaceCharge.getCharge_max();
    double chargeMax2 = chargeMax.doubleValue();
    BigDecimal chargeUnitt = spaceCharge.getCharge_unitt();

    // 获取当前时间
    Calendar calendar = Calendar.getInstance();
    // 定义时间格式化
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    // 停车时间差转换
    Date start = formatter.parse(spaceTime);
    Date end = calendar.getTime();

    // 获得两个时间的毫秒时间差异
    long diff = end.getTime() - start.getTime();

    // 转换分钟时间差
    long minute = diff / 1000 / 60;
    BigDecimal minute_simplify = new BigDecimal(minute);
    double minute1 = minute_simplify.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

    // 定义返回类
    Map<String, Double> totalMap = new HashMap<>();

    double total = 0;
    double total2 = 0;
    double space_chargeUnitt = chargeUnitt.doubleValue();
    totalMap.put("space_chargeUnitt", space_chargeUnitt);

    if (minute < chargeFreeTime) {
      total = 0;
      // 停车费用为0;
    } else {
      double chargeUnitt2 = chargeUnitt.doubleValue() / 60;
      double chargeMin2 = chargeMin.doubleValue();
      double total_simplify = minute * chargeUnitt2;
      BigDecimal total_simplify2 = new BigDecimal(total_simplify);
      total = total_simplify2.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
      if (total <= chargeMin2) { // 价格小于或等于最小价格
        total = chargeMin2;
      } else if (total >= chargeMax2) { // 价格大于最大价格
        total = chargeMax2;
      }
    }
    totalMap.put("space_diff", minute1);
    totalMap.put("spaceTotal", total);
    // 判断车位是否为充电车位
    if (chargeType) {
      double space_chargingUnitt = chargingUnitt.doubleValue();
      totalMap.put("space_chargingUnitt", space_chargingUnitt);
      String chargingStart = spaceAll.getCharging_start();
      String chargingEnd = spaceAll.getCharging_end();
      // 充电时间差转换
      Date charging_start = formatter.parse(chargingStart);
      Date charging_end = formatter.parse(chargingEnd);
      // 获得两个时间的毫秒时间差异
      long charging_diff = charging_end.getTime() - charging_start.getTime();
      long minute2 = charging_diff / 1000 / 60;
      if (total2 < chargingMin2) {
        total2 = chargingMin2;
      }
      BigDecimal minute2_simplify = new BigDecimal(minute2);
      double minute3 = minute2_simplify.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
      totalMap.put("charging_diff", minute3);
      total2 = chargingMin2 + chargingUnitt2 * minute2;
      BigDecimal total2_simplify = new BigDecimal(total2);
      total2 = total2_simplify.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
      totalMap.put("chargingTotal", total2);
    }
    // 总金额
    double totalMoney = total + total2;
    BigDecimal totalMoney_simplify = new BigDecimal(totalMoney);
    double money = totalMoney_simplify.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    totalMap.put("total", money);
    return totalMap;
  }

  // 获取Charge列表
  @Override
  public List<ClientCharge> getChargeList() {
    List<ClientCharge> chargeList = clientMapper.getChargeList();
    return chargeList;
  }

  // 获取Paid列表(15分钟)
  @Override
  public List<Paid> getPaidList() {
    List<Paid> paidRecord = clientMapper.getPaidList();
    return paidRecord;
  }
}
